package com.example.music.adapter;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import com.example.music.R;
import com.example.music.activity.CategoryDetailActivity;
import com.example.music.fragment.CategoryDetailFragment;
import com.example.music.model.CategoryItem;

import java.util.ArrayList;
import java.util.List;

public class CategoryAdapter extends RecyclerView.Adapter<CategoryAdapter.ViewHolder> {
    private List<CategoryItem> categoryList;
    private OnItemClickListener listener;

    public interface OnItemClickListener {
        void onItemClick(CategoryItem item);
    }

    public CategoryAdapter(List<CategoryItem> categoryList, OnItemClickListener listener) {
        this.categoryList = new ArrayList<>(categoryList);
        this.listener = listener;
    }

    @NonNull
    @Override
    public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_category, parent, false);
        return new ViewHolder(view);
    }

    @Override
    public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
        CategoryItem item = categoryList.get(position);
        holder.nameTextView.setText(item.getName());
        holder.countTextView.setText(String.valueOf(item.getCount()));

        holder.itemView.setOnClickListener(v -> {
            listener.onItemClick(item);
        });
    }

    @Override
    public int getItemCount() {
        return categoryList.size();
    }

    public void setCategoryList(List<CategoryItem> categoryList) {
        this.categoryList = new ArrayList<>(categoryList);
        notifyDataSetChanged();
    }

    public void getFilter(String query) {
        List<CategoryItem> filteredList = new ArrayList<>();
        for (CategoryItem item : categoryList) {
            if (item.getName().toLowerCase().contains(query.toLowerCase())) {
                filteredList.add(item);
            }
        }
        setCategoryList(filteredList);
    }

    public static class ViewHolder extends RecyclerView.ViewHolder {
        TextView nameTextView;
        TextView countTextView;

        public ViewHolder(View itemView) {
            super(itemView);
            nameTextView = itemView.findViewById(R.id.category_name);
            countTextView = itemView.findViewById(R.id.category_count);
        }
    }
}